﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;
using Newtonsoft.Json;
using System.Data;
using DevExpress.Web.Mvc;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 信息审核
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class DocumentAuditController : AdminBaseController
    {
        //
        // GET: /Admin/DocumentAudit/

        /// <summary>
        /// 信息类别逻辑类
        /// </summary>
        private BLL.DocCls docClsBLL = new BLL.DocCls();
        /// <summary>
        /// 系统参数逻辑类
        /// </summary>
        private BLL.SysParam sysParamBLL = new BLL.SysParam();
        /// <summary>
        /// 通用方法逻辑类
        /// </summary>
        private BLL.Common commonBLL = new BLL.Common();
        /// <summary>
        /// 信息逻辑类
        /// </summary>
        private BLL.Document documentBLL = new BLL.Document();
        /// <summary>
        /// 模板逻辑类
        /// </summary>
        private BLL.SysTemplate sysTemplateBLL = new BLL.SysTemplate();
        /// <summary>
        /// 权限逻辑类
        /// </summary>
        private BLL.DocClsAuthority docClsAuthorityBLL = new BLL.DocClsAuthority();
        /// <summary>
        /// 员工逻辑类
        /// </summary>
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        /// <summary>
        /// 员工岗位逻辑类
        /// </summary>
        private BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
        /// <summary>
        /// 工作组人员逻辑类
        /// </summary>
        private BLL.HRWorkGrpMember hrWorkGrpMemberBLL = new BLL.HRWorkGrpMember();
        /// <summary>
        /// 附件逻辑类
        /// </summary>
        private BLL.DocAttach docAttachBLL = new BLL.DocAttach();
        /// <summary>
        /// 部门逻辑类
        /// </summary>
        private BLL.HRDept hrDeptBLL = new BLL.HRDept();
        /// <summary>
        /// 信息文档合发单位逻辑类
        /// </summary>
        private BLL.DocumentUnionPubEmpl documentUnionPubEmplBLL = new BLL.DocumentUnionPubEmpl();
        /// <summary>
        /// 
        /// </summary>
        private BLL.DocRecObject docRecObjectBLL = new BLL.DocRecObject();

        /// <summary>
        /// 信息审核
        /// </summary>
        [AuthorityActionFilter("m_DocumentAudit", Order = 1)]
        [LogPageActionFilter("信息审核", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文档列表
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentList(string docClsCd = "", int id = 1)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            ActionResult actionResult = null;
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";
            ViewData["isAuthority"] = false;
            ViewData["isTopSeq"] = false;
            ViewData["isInportEaccount"] = false;
            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetDocumentALLByCTE('" + entityNo + "','" + deptNo + "','" + empNo + "','AUDIT')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetDocumentByCTE('" + docClsCd + "','" + entityNo + "','" + deptNo + "','" + empNo + "','AUDIT')";
                        if (docClsModel.FDocClsProp != BaseStruct.DocClsTypeStruct.EMPTY)
                        {
                            ViewData["isAuthority"] = docClsBLL.ExistsAuthorityDocClsNo(entityNo, empNo, deptNo, "AUDIT", docClsCd);
                        }
                        if (docClsBLL.GetChildeCount(docClsCd, entityNo) == 0)
                        {
                            ViewData["isTopSeq"] = true;
                        }
                    }
                }
            }
            if (docClsModel.FDocClsProp == BaseStruct.DocClsTypeStruct.SINGLE)
            {
                //单信息
                decimal docId = documentBLL.GetDocIdDocClsCd(entityNo, docClsCd);
                if (docId > 0)
                {
                    return RedirectToAction("DocumentAuditEdit", "DocumentPub", new { docId = docId, docClsCd = docClsCd, docType = "MANAGE" });
                }
                else
                {

                }
            }
            else
            {
                //多信息
                //判断是否可以引入文明台账文件
                if (sysParamBLL.GetParamValue("OA_IMPORT_ACCFILE", entityNo) == "Y")
                {
                    ViewData["isInportEaccount"] = true;
                }
                int pageRowSize = 15;
                int pageIndex = id;
                ViewData["pageIndex"] = id - 1;

                string fiedls = "*";
                int total;
                //初始化查询条件
                Models.DocQueryConditionModel conditionModel = new DocQueryConditionModel();
                conditionModel.FStatus = "N";
                string queryWhere = " FStatus='N' AND FRecycle='N'";
                ViewData["docQueryCondition"] = JsonConvert.SerializeObject(conditionModel);
                queryWhere += " AND FIsReference='N'";
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
                List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
                List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

                for (int i = 0; i < total; i++)
                {
                    documentAllList.Add(null);
                }
                for (int i = 0; i < pageRowSize; i++)
                {
                    if (documentList.Count > i)
                    {
                        documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                    }
                }
                if (docClsCd == "")
                {
                    ViewData["docClsPathName"] = "全部类别";
                }
                else
                {
                    ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
                }
                DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);



                actionResult = View("DocumentList", documentListVewModel);
            }
            return actionResult;
        }

        /// <summary>
        /// 文档列表翻页操作
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult DocumentListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());

            string docClsCd = Request.Params["docClsCd"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }

            string entityNo = GlobalConstant.ENTITYNO;
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);

            ViewData["pageIndex"] = pageIndex - 1;

            string fiedls = "*";
            int total;
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";
            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetDocumentALLByCTE('" + entityNo + "','" + deptNo + "','" + empNo + "','AUDIT')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetDocumentByCTE('" + docClsCd + "','" + entityNo + "','" + deptNo + "','" + empNo + "','AUDIT')";
                    }
                }
            }
            ViewData["isAuthority"] = false;
            ViewData["isInportEaccount"] = false;

            //查询条件
            string conditionString = Request.Params["queryCondition"].ToString();
            string queryWhere = " FRecycle='N' ";
            if (conditionString != "")
            {
                Models.DocQueryConditionModel conditionModel = JsonConvert.DeserializeObject<Models.DocQueryConditionModel>(conditionString);
                if (!string.IsNullOrEmpty(conditionModel.FStatus))
                {
                    queryWhere += " AND FStatus='" + Fetch.InspectData(conditionModel.FStatus, CheckGetEnum.Safety) + "'";
                }
                if (!string.IsNullOrEmpty(conditionModel.FIsEnroll))
                {
                    queryWhere += " AND FIsEnroll='" + Fetch.InspectData(conditionModel.FIsEnroll, CheckGetEnum.Safety) + "'";
                }
                if (!string.IsNullOrEmpty(conditionModel.FTitle))
                {
                    if (conditionModel.FTitle.Trim() != "")
                    {
                        queryWhere += " AND FTitle Like '%" + Fetch.InspectData(conditionModel.FTitle, CheckGetEnum.Safety) + "%'";
                    }
                }
                if (conditionModel.BeginPubDate.HasValue && conditionModel.EndPubDate.HasValue)
                {
                    queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0 AND DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";
                }
                else
                {
                    if (conditionModel.BeginPubDate.HasValue)
                    {
                        queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0";
                    }
                    else
                    {
                        if (conditionModel.EndPubDate.HasValue)
                        {
                            queryWhere += " AND  DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";

                        }
                    }
                }
                if (conditionModel.PubEmplList != null && conditionModel.PubEmplList.Count > 0)
                {
                    // 目前支持单用户选择
                    string emplNo = conditionModel.PubEmplList[0].Value;
                    queryWhere += " AND FEmplNo='" + emplNo + "'";
                }
                if (conditionModel.DeptList != null && conditionModel.DeptList.Count > 0)
                {
                    // 目前支持单部门选择
                    string queryDeptNo = conditionModel.DeptList[0].Value;
                    queryWhere += " AND FDeptNo='" + queryDeptNo + "'";
                }
                if (conditionModel.WorkGroupList != null && conditionModel.WorkGroupList.Count > 0)
                {
                    // 目前支持单部门选择
                    string workGrpNo = conditionModel.WorkGroupList[0].Value;
                    queryWhere += " AND FWorkGrpNo='" + workGrpNo + "'";
                }
            }
            queryWhere += " AND FIsReference='N'";
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
            List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
            List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            for (int i = 0; i < total; i++)
            {
                documentAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (documentList.Count > i)
                {
                    documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                }
            }
            DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);
            bool isAuthority = docClsBLL.ExistsAuthorityDocClsNo(entityNo, empNo, deptNo, "AUDIT", docClsCd);
            ViewData["isAuthority"] = isAuthority;
            if (docClsCd == "")
            {
                ViewData["docClsPathName"] = "全部类别";
            }
            else
            {
                ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
            }
            return PartialView("DocumentListPartial", documentListVewModel);
        }
        /// <summary>
        /// 删除文档（放入回收站）
        /// </summary>
        /// <param name="docIds"></param>
        /// <returns></returns>
        [HttpPost]
        public string RecycleDocument(string docIds)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;
            string[] docIdArray = docIds.Split(',');
            if (docIdArray.Length > 0)
            {
                try
                {
                    List<decimal> docIdList = new List<decimal>();
                    bool isSuccess = true;
                    foreach (string s in docIdArray)
                    {
                        decimal tmp = 0;
                        if (decimal.TryParse(s, out tmp))
                        {
                            docIdList.Add(tmp);
                        }
                        else
                        {
                            isSuccess = false;
                            break;
                        }
                    }
                    if (!isSuccess)
                    {
                        errorMessage = "信息编号参数解析错误";
                    }
                    else
                    {
                        string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                        documentBLL.UpdateDocumentRecycle(docIdList, empNo);
                        jsonstr = "SUCCESS";
                    }
                }
                catch (Exception ee)
                {
                    errorMessage = "操作异常:" + ee.Message;
                }
            }
            else
            {
                errorMessage = "信息编号参数错误";
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
    }
}
